package br.com.intelsys.security.itoken;

import java.util.Date;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import br.com.intelsys.basics.dao.DaoException;
import br.com.intelsys.basics.dao.hiber.DaoHiber;
import br.com.intelsys.basics.utils.Knife;
import br.com.intelsys.security.itoken.IToken.Status;

@Component
public class ITokenDao extends DaoHiber {
	private static final Log log = LogFactory.getLog(ITokenDao.class);

	@Autowired
	public ITokenDao(SessionFactory sessionFactory) {
		super(sessionFactory);
	}

	IToken getIToken(int codITokenType, int codOwner, int codAux, int usesMax, Date dateExpire) {
		ITokenHiber t = new ITokenHiber();
		t.setITokenType(getITokenType(codITokenType));
		t.setCodOwner(codOwner);
		t.setCodAux(codAux);
		t.setUsesMax(usesMax);
		t.setStatus(Status.ON);
		t.setDateExpires(dateExpire);
		return t;
	}

	IToken getIToken(int codIToken) {
		return (IToken) getQueryManager().get(ITokenHiber.class, codIToken);
	}

	ITokenType getITokenType(int codITokenType) {
		return (ITokenType) getQueryManager().get(ITokenTypeHiber.class, codITokenType);
	}

	void saveIToken(IToken token) throws DaoException {
		if (token != null) {
			if (token.getCodIToken() == 0) {
				((ITokenHiber) token).setToken(generateHashToken(token.getITokenType()));
			}
			getQueryManager().saveOrUpdate(token);
		}
	}

	private String generateHashToken(ITokenType iTokenType) {
		String token;
		do {
			token = Knife.getMD5(Long.toString(System.currentTimeMillis()) + '#' + iTokenType.getSecretKey());
			if (log.isDebugEnabled()) {
				log.debug("Criando token: " + token);
			}
		} while (getIToken(token) != null);
		return token;
	}

	IToken getIToken(String token) {
		return (IToken) getQueryManager().find("br.com.intelsys.security.itoken.ITokenHiber.getTokenByToken").param("token", token)
				.getUniqueValue();
	}

	@SuppressWarnings("unchecked")
	List<IToken> getITokenListFromTypeOwnerAuxAndStatusOn(int codITokenType, int codOwner, int codAux) {
		return getQueryManager().find("br.com.intelsys.security.itoken.ITokenHiber.getITokenListFromOwnerAndTypeStatusOn")
				.param("codType", codITokenType).param("codOwner", codOwner).param("codAux", codAux).param("status", "ON").getList();
	}
}
